package com.windowes.weichang.service;

import com.google.gson.Gson;
import com.windowes.weichang.common.BDConfig;
import com.windowes.weichang.common.BDResponse;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.model.BDShop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.math.BigDecimal;
import java.util.List;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/6/17 下午8:16
 * @description:
 *
 **/
@Service
@Slf4j
public class BDMapService {

    public static final String CREATETABLE = "http://api.map.baidu.com/geodata/v4/geotable/create";
    public static final String LIST = "http://api.map.baidu.com/geodata/v4/geotable/commentList";
    public static final String COLUMN_CREATE = "http://api.map.baidu.com/geodata/v4/column/create";

    public static final String POI_CREATE = "http://api.map.baidu.com/geodata/v4/poi/create";
    public static final String SEARCH_POI = "http://api.map.baidu.com/geosearch/v4/nearby";
    public static final String GEO_SEARCH = "http://api.map.baidu.com/geosearch/v4/local";

    public static final String geotable_id = "1000004086";


    @Autowired
    BDConfig bdConfig;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 创建表【百度】
     *
     * @param tableName
     * @param isPublished
     * @return
     */
    public ServerResponse createTable(String tableName, int isPublished) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("name", tableName);
        map.add("is_published", isPublished + "");
        map.add("ak", bdConfig.getAk());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(CREATETABLE, request, String.class);
        if (stringResponseEntity.getStatusCode() == HttpStatus.OK) {
            return ServerResponse.createBySuccessMessage("创建成功!");
        }
        return ServerResponse.createByErrorMessage("创建失败!");
    }

    /**
     * 所有表【百度】
     *
     * @param tableName
     * @return
     */
    public ServerResponse list(String tableName) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("name", tableName);
        map.add("ak", bdConfig.getAk());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(LIST, request, String.class);
        if (stringResponseEntity.getStatusCode() == HttpStatus.OK) {
            BDResponse bdResponse = new Gson().fromJson(stringResponseEntity.getBody(), BDResponse.class);
            return ServerResponse.createBySuccess("获取成功!", bdResponse.getGeotables());
        }
        return ServerResponse.createByErrorMessage("获取失败!");
    }


    /**
     * 创建列【百度】
     *
     * @param name       column的名称描述
     * @param key        column存储的key标识，含义与返回结果中的列“id”字段相同，该字段为用户创建时自定义设置
     * @param type       枚举值1：Int64, 2：double, 3：string, 4：在线图片url
     * @param geoTableId
     * @return
     */
    public ServerResponse columnCreate(String name, String key, String type, String geoTableId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("key", key);
        map.add("type", type);
        map.add("is_search_field", "1");
        map.add("is_index_field", "1");
        map.add("geotable_id", geoTableId);
        map.add("ak", bdConfig.getAk());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(COLUMN_CREATE, request, String.class);
        if (stringResponseEntity.getStatusCode() == HttpStatus.OK) {
            return ServerResponse.createBySuccess("column创建成功!");
        }
        return ServerResponse.createByErrorMessage("column获取失败!");
    }


    /**
     * 数据同步【百度】
     *
     * @param title
     * @param address
     * @param longitude
     * @param latitude
     * @param shopkeeper
     * @param shopId
     * @return
     */
    public ServerResponse dsJob(String title, String address, BigDecimal longitude, BigDecimal latitude, String shopkeeper, Integer shopId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("longitude", longitude + "");
        map.add("latitude", latitude + "");
        map.add("address", address);
        map.add("shopkeeper", shopkeeper);
        map.add("shop_id", shopId + "");
        map.add("title", title);

        map.add("geotable_id", geotable_id);
        map.add("ak", bdConfig.getAk());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(POI_CREATE, request, String.class);
        log.info("同步结果为:{}", stringResponseEntity.getBody());
        if (stringResponseEntity.getStatusCode() == HttpStatus.OK) {
            return ServerResponse.createBySuccessMessage("创建成功!");
        }
        return ServerResponse.createByErrorMessage("创建失败!");
    }

    /**
     * POI搜索【百度】
     *
     * @param location 116.395884,39.932154
     * @param radius   1000
     * @param tags     酒店
     * @return
     */
    public ServerResponse<List<BDShop>> search(String location, String radius, String tags, String q) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(SEARCH_POI)
                .queryParam("ak", bdConfig.getAk())
                .queryParam("geotable_id", geotable_id)
                .queryParam("location", location)
                .queryParam("radius", radius)
                .queryParam("sortby", "distance:1")
                .queryParam("q", q)
                .queryParam("coord_type", "3")
                .queryParam("page_index", 0)
                .queryParam("page_size", 100);

        HttpEntity<?> entity = new HttpEntity<>(headers);
        HttpEntity<String> response = restTemplate.exchange(
                builder.build().encode().toUri(),
                HttpMethod.GET,
                entity,
                String.class);

        BDResponse bdResponse = new Gson().fromJson(response.getBody(), BDResponse.class);
        if (bdResponse != null && bdResponse.getContents() != null && !bdResponse.getContents().isEmpty()) {
            return ServerResponse.createBySuccess(bdResponse.getContents());
        }
        return ServerResponse.createByErrorMessage("未查询到相关店铺");
    }


    /**
     * 附近搜索【百度】
     *
     * @param region 北京
     * @param tags   酒店
     * @return
     */
    public ServerResponse<List<BDShop>> geosearch(String region, String tags) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(GEO_SEARCH)
                .queryParam("ak", bdConfig.getAk())
                .queryParam("geotable_id", geotable_id)
                .queryParam("tags", tags)
                .queryParam("region", region)
                .queryParam("coord_type", "3")
                .queryParam("page_index", 0)
                .queryParam("page_size", 100);

        HttpEntity<?> entity = new HttpEntity<>(headers);
        HttpEntity<String> response = restTemplate.exchange(
                builder.build().encode().toUri(),
                HttpMethod.GET,
                entity,
                String.class);

        BDResponse bdResponse = new Gson().fromJson(response.getBody(), BDResponse.class);
        if (bdResponse != null && bdResponse.getContents() != null && !bdResponse.getContents().isEmpty()) {
            return ServerResponse.createBySuccess(bdResponse.getContents());
        }
        return ServerResponse.createByErrorMessage("未查询到相关店铺");
    }


}
